<template>
  <div class="no-background-container">
    <el-affix :offset="0">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">
            {{ routeName }}
          </div>
        </div>
        <div class="header-query">
          <div class="action-buttons">
            <el-button type="primary" @click="handleSave">保存议程</el-button>
          </div>
        </div>
      </div>
    </el-affix>

    <div class="agenda-content">
      <div class="editor-section">
        <el-form ref="formRef" label-width="100px" :model="agendaData">
          <el-form-item label="议程内容" prop="richText">
            <quill-editor v-model="editorContent" class="agenda-editor" placeholder="请输入议程内容" @blur="handleEditorBlur" />
          </el-form-item>
        </el-form>
      </div>
      <div class="attachment-section">
        <div class="attachment-header">
          <h3>日程文件列表</h3>
          <div class="attachment-stats">
            <span class="stat-item">总数: {{ agendaData.attachment?.length || 0 }}</span>
          </div>
        </div>
        <div v-if="agendaData.attachment && agendaData.attachment.length > 0" class="attachment-list">
          <div v-for="(item, index) in agendaData.attachment" :key="index" class="attachment-item">
            <div class="file-info">
              <div class="file-icon">
                <i :class="getFileIcon(item.fileName)"></i>
              </div>
              <div class="file-details">
                <div class="file-name">{{ item.fileName }}</div>
                <div class="file-meta">{{ formatFileSize(item.size) }}</div>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button size="small" text type="primary" @click="handleDownload(item)">
                <el-icon><download /></el-icon>
              </el-button>
              <el-button size="small" text type="danger" @click="handleRemoveAttachment(index)">
                <el-icon><delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无附件" />
        <div class="upload-section">
          <my-file-upload v-model="currentFile" :file-types="fileTypes" text="点击上传会议附件" @update:model-value="handleFileChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Delete, Download } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import Public from '~/src/api/public/index.ts'
import MyFileUpload from '~/src/components/MyFileUpload/index.vue'
import QuillEditor from '~/src/components/quill/QuillEditor.vue'
import { moduleApi } from './config.ts'

// 获取当前路由对象
const route = useRoute()

// 使用markRaw避免Vue警告
const activityId = ref(localStorage.getItem('hongyouActId') || '')

// 计算属性，获取路由名称
const routeName = computed(() => route.meta.title || '议程管理')

// 表单引用
const formRef = ref<FormInstance>()

// 扩展Agenda接口
interface ExtendedAgenda {
  id?: number
  activityId: string
  fileName: string
  filePreview: string
  remark: string
  richText?: string | null
  attachment?: any[]
  fileUrl?: string | null
}

// 初始化单条议程数据
const agendaData = ref<ExtendedAgenda>({
  activityId: activityId.value,
  fileName: '',
  richText: '',
  filePreview: '',
  remark: '',
  attachment: [],
  fileUrl: null,
  id: undefined,
})

// 加载状态
const loading = ref<boolean>(false)

// 富文本编辑器失去焦点事件
const handleEditorBlur = () => {
  formRef.value?.validateField('filePreview')
}

// 获取议程数据
const fetchAgendaData = async () => {
  if (!activityId.value) {
    ElMessage.warning('未找到活动ID，请先创建活动')
    return
  }

  loading.value = true
  try {
    const response = await Public.getDetailApi({
      url: moduleApi,
      params: {
        activityId: activityId.value,
        page: 1,
        limit: 1,
      },
    })

    const { code, result } = response as any

    if (code === 0 && result && result.rows && result.rows.length > 0) {
      // 获取第一条数据
      const data = result.rows[0]
      agendaData.value = {
        ...data,
        activityId: activityId.value,
        // 确保attachment字段存在
        attachment: data.attachment || [],
      }
      console.log('加载现有议程数据:', agendaData.value)
    } else {
      // 没有数据，使用默认值
      console.log('未找到现有议程数据，准备创建新的议程')
      agendaData.value = {
        activityId: activityId.value,
        fileName: '',
        filePreview: '',
        remark: '',
        attachment: [],
        richText: null,
        fileUrl: null,
        id: undefined,
      }
    }
  } catch (error) {
    console.error('获取议程数据失败:', error)
    ElMessage.error('获取议程数据失败')
  } finally {
    loading.value = false
  }
}

// 保存议程
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const formData = { ...agendaData.value }

        let response
        if (formData.id) {
          // 编辑现有数据
          response = await Public.editApi({ url: moduleApi, data: formData })
          console.log('更新议程数据:', response)
          ElMessage.success('议程已更新')
        } else {
          // 创建新数据
          response = await Public.addApi({ url: moduleApi, data: formData })
          console.log('创建议程数据:', response)
          ElMessage.success('议程已创建')
          // 重新获取数据以获取ID
          fetchAgendaData()
        }
      } catch (error) {
        console.error('保存议程失败:', error)
        ElMessage.error('保存议程失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 文件上传相关
const currentFile = ref('')
const fileTypes = ref(
  '.doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.txt,.rtf,' +
    '.jpg,.jpeg,.png,.gif,.bmp,.svg,.webp,' +
    '.zip,.rar,.7z,' +
    '.mp3,.wav,.mp4,.avi,.mov'
)

// 处理文件变更
const handleFileChange = (url: string) => {
  if (url) {
    // 如果上传了新文件
    const fileName = url.split('/').pop() || '未命名文件'

    // 确保attachment是数组
    if (!Array.isArray(agendaData.value.attachment)) {
      agendaData.value.attachment = []
    }

    // 添加新上传的文件到附件列表
    agendaData.value.attachment.push({
      name: fileName,
      url,
      size: 0,
    })

    ElMessage.success('文件上传成功')

    // 如果已有ID，自动保存附件信息
    if (agendaData.value.id) {
      handleSave()
    }

    // 重置当前文件，使上传组件准备好接收下一个文件
    currentFile.value = ''
  }
}

// 下载附件
const handleDownload = (item: any) => {
  if (item.url) {
    window.open(item.url, '_blank')
  } else {
    ElMessage.warning('文件链接不存在')
  }
}

// 删除附件
const handleRemoveAttachment = (index: number) => {
  ElMessageBox.confirm('确定要删除这个附件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      agendaData.value.attachment!.splice(index, 1)
      ElMessage.success('附件已删除')

      // 如果已有ID，自动保存附件信息
      if (agendaData.value.id) {
        handleSave()
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 文件图标辅助函数
const getFileIcon = (fileName: string) => {
  console.log('fileName', fileName)
  const ext = fileName.split('.').pop()?.toLowerCase() || ''
  const iconMap: Record<string, string> = {
    // 文档
    doc: 'el-icon-document',
    docx: 'el-icon-document',
    pdf: 'el-icon-document',
    txt: 'el-icon-document',
    rtf: 'el-icon-document',

    // 表格
    xls: 'el-icon-document',
    xlsx: 'el-icon-document',

    // 演示文稿
    ppt: 'el-icon-document',
    pptx: 'el-icon-document',

    // 图片
    jpg: 'el-icon-picture',
    jpeg: 'el-icon-picture',
    png: 'el-icon-picture',
    gif: 'el-icon-picture',
    bmp: 'el-icon-picture',
    svg: 'el-icon-picture',
    webp: 'el-icon-picture',

    // 压缩文件
    zip: 'el-icon-document',
    rar: 'el-icon-document',
    '7z': 'el-icon-document',

    // 音频
    mp3: 'el-icon-headset',
    wav: 'el-icon-headset',

    // 视频
    mp4: 'el-icon-video-camera',
    avi: 'el-icon-video-camera',
    mov: 'el-icon-video-camera',
  }

  return iconMap[ext] || 'el-icon-document'
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '未知大小'

  if (size < 1024) {
    return `${size} B`
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`
  } else {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`
  }
}

// 创建计算属性处理richText
const editorContent = computed({
  get: () => agendaData.value.richText || '',
  set: (val: string) => {
    agendaData.value.richText = val
  },
})

// 监听activityId变化
watch(activityId, (newVal) => {
  if (newVal) {
    fetchAgendaData()
  }
})

// 组件激活时获取数据
onActivated(() => {
  fetchAgendaData()
})

// 组件挂载前初始化数据
onBeforeMount(() => {
  fetchAgendaData()
})
</script>

<style lang="scss" scoped>
.agenda-container {
  min-height: 100%;
  padding-bottom: 20px;
}

.agenda-content {
  display: flex;
  margin-top: 20px;
  min-height: calc(100vh - 120px);
  background-color: #fff;
  padding: 20px;
  border-radius: 5px 0 0 0;
  border: 1px solid #e5ecf0;
}

.editor-section {
  width: 70%;
  padding-right: 20px;

  .agenda-editor {
    height: 400px;
  }
}

.attachment-section {
  width: 30%;
  padding-left: 20px;
  border-left: 1px solid #ebeef5;

  .attachment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-weight: 500;
      color: #333;
    }

    .attachment-stats {
      display: flex;
      gap: 10px;

      .stat-item {
        font-size: 14px;
        color: #606266;
        background-color: #f5f7fa;
        padding: 2px 8px;
        border-radius: 12px;
      }
    }
  }

  .attachment-list {
    margin-bottom: 20px;
    max-height: 340px;
    overflow-y: auto;
    padding-right: 5px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #e0e0e0;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
    }
  }

  .attachment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    margin-bottom: 10px;
    background-color: #f5f7fa;
    border-radius: 6px;
    transition: all 0.2s ease;
    border-left: 3px solid #409eff;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .file-info {
      display: flex;
      align-items: center;
      overflow: hidden;
      flex: 1;

      .file-icon {
        margin-right: 10px;
        font-size: 18px;
        color: #606266;
      }

      .file-details {
        overflow: hidden;

        .file-name {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 160px;
        }

        .file-meta {
          font-size: 12px;
          color: #909399;
          margin-top: 2px;
        }
      }
    }

    .attachment-actions {
      display: flex;
      gap: 5px;
    }
  }

  .upload-section {
    margin-top: 20px;
    border-top: 1px dashed #dcdfe6;
    padding-top: 20px;
  }
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
